/////////////////////////////////////////////////////////////////////
//  Package Description:
//    BBC iPlayer plugin for MythTV by Grant French (c) 2008-2009
//
//  Filename:  qnetpixmap.cpp
//  Author:    Grant French
//  Date:      06/12/2008
//
//  Description:
//    Download image and make available as a QT image object.
//
/////////////////////////////////////////////////////////////////////

#include "qnetpixmap.h"

QNetPixmap::QNetPixmap(const QString &image_url) : QObject()
{
  // initialise flags used for downloading data
  errorFlag = false;
  processingDownload = false;

  // create the download buffers etc. and attach to the requestFinished signal
  QUrl url( image_url );
  http = new QHttp();
  buff = new QBuffer(bytes);
  QObject::connect( http, SIGNAL(requestFinished(int, bool)), this, SLOT(httpFinished(int, bool)));

  // exit if we can't open the buffer
  if ( !buff->open(IO_WriteOnly) ) return;

  printf("iplayer: Downloading %s\n",image_url.ascii());

  // flag that we are now processing the download
  processingDownload = true;

  // set the host and perform the HTTP get request
  http->setHost(url.host());
  iRequest = http->get(url.path(),buff);

  // wait for download to complete (but be nice)
  while(processingDownload) { qApp->processEvents(); };

  // if an error occurred during the download, dont process the data
  if (errorFlag) {
    printf("iplayer: QHttp error occurred.\n");
    return;
  }

  // create an image object from the data we downloaded
  image.loadFromData( bytes );

}

void QNetPixmap::httpFinished(int reqId, bool error)
{
  // if an error occurred during the download flag it
  //  and flag the end of the download.
  if (error) {
    errorFlag = true;
    processingDownload = false;

  }

  // if this signal was sent for the request we are waiting on
  //  then flag the end of the download and remove the signal handler.
  else if (reqId==iRequest)
  {
    processingDownload = false;
    disconnect( http, SIGNAL(requestFinished(int, bool)), 0, 0 );

  }

}

QNetPixmap::~QNetPixmap()
{
}


